/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.read;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ReflectUtil;
import cn.star.framework.core.IEntity;
import cn.star.framework.core.IService;
import cn.star.framework.excel.core.Column;
import cn.star.framework.excel.core.RowType;
import cn.star.framework.excel.core.RowWrapper;
import cn.star.framework.excel.read.ReadContext;
import cn.star.framework.excel.read.ReadRowCallback;
import cn.star.framework.excel.read.SimpleReadRowCallback;
import cn.star.framework.excel.read.status.RowStatus;
import cn.star.framework.excel.read.status.SheetStatus;
import cn.star.framework.strategy.UpdateStrategy;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;

/**
 * {@link ReadRowCallback}实现类<br>
 * 读取Excel数据后的回调函数，将数据持久化到数据库<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Slf4j
public class SaveOrUpdateReadRowCallback<T extends IEntity, Id extends Serializable>
    extends SimpleReadRowCallback {
  private final IService<T, Id> service;
  private final Class<T> type;

  public SaveOrUpdateReadRowCallback(IService<T, Id> service, Class<T> type) {
    this.service = service;
    this.type = type;
  }

  @Override
  @SuppressWarnings("all")
  protected void invoke(SheetStatus sheetStatus, RowWrapper wrapper) {
    Map<String, Object> data = wrapper.getData();
    List<Column> columns = wrapper.getColumns();
    // 如果数据为空，则终止本次处理，可能是由于某种原因导致的无效数据
    if (CollectionUtil.isEmpty(data) || wrapper.getType() == RowType.BLANK) {
      sheetStatus.addRowStatus(new RowStatus(wrapper.getIndex(), RowType.BLANK, true));
      return;
    }
    // 如果列集合为空，则需要抛出异常
    Assert.isFalse(
        CollectionUtil.isEmpty(columns),
        "The column set (# columns) in {} is empty, unknown error",
        ReadContext.class.getSimpleName());
    // 数据处理
    Set<String> keys = data.keySet();
    T entity = ReflectUtil.newInstance(type);
    for (String key : keys) {
      Column column = columns.stream().filter(i -> key.equals(i.getKey())).findFirst().orElse(null);
      if (column == null) {
        log.warn(
            "⭕ -> line number: {}, field name used: ({}) did not obtain ({})",
            wrapper.getIndex(),
            key,
            Column.class.getSimpleName());
        continue;
      }
      try {
        // 处理数据，包括数据转换和数据校验
        this.setRowInstanceColumValue(entity, column, wrapper);
      } catch (Exception e) {
        String type = e.getClass().getName();
        String message = e.getMessage();
        sheetStatus.addRowStatus(
            new RowStatus(wrapper.getIndex(), RowType.DATA, false, type, message));
        log.error("persistence before error, type: {}, message: {}", type, message);
        return;
      }
    }
    try {
      this.merge(entity, wrapper);
      this.service.save(entity, UpdateStrategy.IGNORE_VERSION);
      sheetStatus.addRowStatus(new RowStatus(wrapper.getIndex(), RowType.DATA, true));
    } catch (Exception e) {
      String type = e.getClass().getName();
      String message = e.getMessage();
      sheetStatus.addRowStatus(
          new RowStatus(wrapper.getIndex(), RowType.DATA, false, type, message));
      log.error("persistence error, type: {}, message: {}", type, message);
    }
  }

  @SuppressWarnings("all")
  private void merge(T entity, RowWrapper wrapper) {
    try {
      T oldEntity = this.service.findById(entity);
      // 应该将不在 wrapper#columns 中的字段重新从旧数据中取得，防止到原先字段上
      if (oldEntity != null) {

        Field[] fields = ReflectUtil.getFields(oldEntity.getClass());
        List<String> names =
            wrapper.getColumns().stream().map(Column::getKey).collect(Collectors.toList());
        for (Field field : fields) {
          if (!names.contains(field.getName())) {
            try {
              ReflectUtil.setFieldValue(entity, field, ReflectUtil.getFieldValue(oldEntity, field));
            } catch (Exception e) {
              // 忽略异常
            }
          }
        }
      }
    } catch (Exception e) {
      // 忽略异常
    }
  }
}
